//
//  GrabOrderMainVC.m
//  LogisticsSupplier
//
//  Created by 吕晶 on 2021/3/15.
//  Copyright © 2021 吕晶. All rights reserved.
//

#import "GrabOrderMainVC.h"
#import "GrabOrder_NavBar.h"
#import "GrabOrderMainCell.h"
#import "GrabOrderMainModel.h"
#import "TaskManagerMainVC.h"

@interface GrabOrderMainVC () <UITableViewDelegate,UITableViewDataSource> {
    int page;
    NSString *ck_id;//抢单的仓库ID
}

@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) GrabOrder_NavBar *navBar;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray <GrabOrderMainModel *>*dataArray;
@property (nonatomic, strong) NSTimer *timer;

@end

@implementation GrabOrderMainVC

-(NSMutableArray<GrabOrderMainModel *> *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.navBar.nim_bottom, ScreenW, ScreenH - TabbarHeight - self.navBar.nim_bottom) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        __weak_self;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            __strong_self;
            strongSelf->page = 1;
            [strongSelf requestForList];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            __strong_self;
            strongSelf->page++;
            [strongSelf requestForList];
        }];
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"img_occupy"
                                                            titleStr:@""
                                                           detailStr:@""];
    }
    return _tableView;
}

-(UIView *)bgView {
    if (!_bgView) {
        _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, NaviHeight + 111)];
        _bgView.backgroundColor = Color_ThemeColor;
        [_bgView setRadianLayer:DXRadianDirectionBottom Radius:20];
    }
    return _bgView;
}

-(GrabOrder_NavBar *)navBar {
    if (!_navBar) {
        _navBar = [[GrabOrder_NavBar alloc] initWithFrame:CGRectMake(0, StatusBarHeight, ScreenW, NaviHeight - StatusBarHeight)];
    }
    return _navBar;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    page = 1;
    ck_id = @"";
    self.navigationController.navigationBar.hidden = YES;
    [self.view addSubview:self.bgView];
    [self.view addSubview:self.navBar];
    [self.view addSubview:self.tableView];
    [self requestForList];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshList) name:ReceiptDeliveryRefreshGrabOrderList object:nil];
}

- (void)refreshList {
    page = 1;
    [self requestForList];
}

- (void)requestForList {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:@(page) forKey:@"page"];
    [HttpRequest PostWithApi:LogisticsSupplierGrabOrderList params:dic progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            if (self->page == 1) {
                [self.dataArray removeAllObjects];
                self.dataArray = [GrabOrderMainModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
            }else {
                NSArray *array = [GrabOrderMainModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
                [self.dataArray addObjectsFromArray:array];
            }
            BOOL has_more = [responseObject[@"has_more"] boolValue];
            if (has_more) {
                self.tableView.mj_footer.hidden = NO;
            }else {
                self.tableView.mj_footer.hidden = YES;
            }
            [self.tableView reloadData];
            [self stopTimer];
            [self startTimer];
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    } fail:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

//开启定时器
-(void)startTimer {
     if (!self.timer) {
          self.timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                        target:self
                                                      selector:@selector(timerLoop)
                                                      userInfo:nil
                                                       repeats:YES];
          [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
     }
}

//停止定时器
-(void)stopTimer {
     if (self.timer) {
          [self.timer invalidate];
          self.timer = nil;
     }
}
//计时
-(void)timerLoop {
    [self.dataArray enumerateObjectsUsingBlock:^(GrabOrderMainModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.countdown > 0) {
            obj.countdown -= 1;
            GrabOrderMainCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:idx inSection:0]];
            [cell configWithTime:obj.countdown];
        }
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GrabOrderMainModel *model = self.dataArray[indexPath.row];
    GrabOrderMainCell *cell = [GrabOrderMainCell GrabOrderMainCellWithTableView:tableView];
    cell.model = model;
    __weak_self;
    cell.grabBlock = ^{
        [weakself grabOrderClick:model];
    };
    return cell;
}

- (void)grabOrderClick:(GrabOrderMainModel *)model {
    if (model.is_receie == 1) {
        if (model.sup_address.count) {
            if (model.sup_address.count > 1) {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
                [model.sup_address enumerateObjectsUsingBlock:^(GrabOrderAddressModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    UIAlertAction *action1 = [UIAlertAction actionWithTitle:obj.info style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        self->ck_id = obj.Id;
                        [self requestForGrabOrder:model.sta_id withCk_id:self->ck_id];
                    }];
                    [alert addAction:action1];
                }];
                UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

                }];
                [alert addAction:cancle];
                [self presentViewController:alert animated:YES completion:nil];
            }else {
                ck_id = model.sup_address.firstObject.Id;
                [self requestForGrabOrder:model.sta_id withCk_id:ck_id];
            }
        }
    }else {
        [self requestForGrabOrder:model.sta_id withCk_id:nil];
    }
}

- (void)requestForGrabOrder:(NSString *)sta_id withCk_id:(NSString *)ck_id {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:sta_id forKey:@"sta_id"];
    if (ck_id) {
        [dic setObject:ck_id forKey:@"ck_id"];
    }
    [HttpRequest PostWithApi:LogisticsSupplierGrabOrder params:dic progress:^(NSProgress * _Nonnull progress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            [self refreshList];
            if (errorCode == 1) {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"抢单成功" message:@"请到我的任务中处理任务。点击下方的“去我的任务”可直接跳转到我的任务中。" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"去我的任务" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    TaskManagerMainVC *vc = [TaskManagerMainVC new];
                    vc.hidesBottomBarWhenPushed = YES;
                    [self.rt_navigationController pushViewController:vc animated:YES];
                }];
                [sureAction setValue:Color_ThemeColor forKey:@"titleTextColor"];
                UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"关闭" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [cancleAction setValue:HexColor(0x585974) forKey:@"titleTextColor"];
                [alert addAction:sureAction];
                [alert addAction:cancleAction];
                [self presentViewController:alert animated:YES completion:nil];
            }else if (errorCode == 20014) {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"抢单失败" message:responseObject[@"msg"] preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"关闭" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [cancleAction setValue:Color_ThemeColor forKey:@"titleTextColor"];
                [alert addAction:cancleAction];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    GrabOrderMainModel *model = self.dataArray[indexPath.row];
    GrabOrderMainCell *cell = [GrabOrderMainCell GrabOrderMainCellWithTableView:tableView];
    cell.model = model;
    return cell.height;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
//    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
//    view.backgroundColor = Color_backgroundColor;
//    return view;
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0;
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self stopTimer];
}

@end
